//
//  LeftViewController.m
//  OtakuWorld
//
//  Created by iOS Two on 14-9-19.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "LeftViewController.h"
#import "NewsViewController.h"
#import "UIImageView+MJWebCache.h"
#import "MJRefresh.h"
#import "InfoViewController.h"

@interface LeftViewController ()

@end

@implementation LeftViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [MobClick endLogPageView:@"LeftViewController"];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    _i = 1;
    _j = 1;
    _isleft = YES;

    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated {
    [MobClick beginLogPageView:@"LeftViewController"];

    [super.navigationController setNavigationBarHidden:YES animated:TRUE];
    [super.navigationController setToolbarHidden:YES animated:TRUE];
    if (_infoArray.count == 0) {
        [self getData];
    }
}
-(void)creatController {
    UIView *ccc = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 64)];
    ccc.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:ccc];
    
    _left = [UIButton buttonWithType:UIButtonTypeCustom];
    [_left setTitle:@"要闻" forState:UIControlStateNormal];
    _left.layer.masksToBounds = YES;
    _left.layer.cornerRadius = 6.0;
    _left.layer.borderWidth = 1.0;
    _left.tag = 1;
    [_left addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
    _left.layer.borderColor = [[UIColor whiteColor] CGColor];
    _left.backgroundColor = [UIColor colorWithRed:0.93 green:0.42 blue:0.29 alpha:1];
    [_left setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _left.frame = CGRectMake(3, 20, 155.5, 45);
    [self.view addSubview:_left];
    
    _right = [UIButton buttonWithType:UIButtonTypeCustom];
    [_right setTitle:@"资讯" forState:UIControlStateNormal];
    _right.layer.masksToBounds = YES;
    _right.layer.cornerRadius = 6.0;
    _right.layer.borderWidth = 1.0;
    _right.tag = 2;
    [_right addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
    _right.layer.borderColor = [[UIColor whiteColor] CGColor];
    _right.backgroundColor = [UIColor colorWithRed:0.9 green:0.76 blue:0.56 alpha:1];
    [_right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _right.frame = CGRectMake(163, 20, 155.5, 45);
    [self.view addSubview:_right];
    
    _back = [[UIImageView alloc]initWithFrame:CGRectMake(0, 61, 320, 3)];
    _back.backgroundColor = [UIColor colorWithRed:0.93 green:0.42 blue:0.29 alpha:1];
    [self.view addSubview:_back];
    
    NSMutableArray *viewsArray = [[NSMutableArray alloc]init];
    for (int i = 0; i < 3; i++) {
        UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 150)];
        
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 150)];
        image.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 108, 320, 20)];
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor whiteColor];
        if (_topImgArray.count != 0) {
            [image setImageURLStr:[_topImgArray objectAtIndex:i] placeholder:[UIImage imageNamed:@"img_newdish"]];
            
            label.text = [_topTitleArray objectAtIndex:i];
        }
        [back addSubview:image];
        //[back addSubview:label];
        [viewsArray addObject:back];
    }
    _mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 150) animationDuration:3];
    _mainScorllView.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];
    _mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    _mainScorllView.totalPagesCount = ^NSInteger(void){
        return 3;
    };
    _mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
        [MobClick event:@"clickAdvTimes"];
        [self clickAdv:pageIndex];
        NSLog(@"点击了第%d个",pageIndex);
    };
    
    _mainTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 320, kHeight - 64 - 49) style:UITableViewStylePlain];
    _mainTable.delegate = self;
    _mainTable.dataSource = self;
    _mainTable.rowHeight = 67;
    _mainTable.tableHeaderView = _mainScorllView;
    [self.view addSubview:_mainTable];
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//    [_mainTable addHeaderWithTarget:self action:@selector(headerRereshing)];
#warning 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_mainTable addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    _mainTable.headerPullToRefreshText = @"下拉可以刷新了";
//    _mainTable.headerReleaseToRefreshText = @"松开马上刷新了";
//    _mainTable.headerRefreshingText = @"正在刷新中";
    
    _mainTable.footerPullToRefreshText = @"上拉可以加载更多数据了";
    _mainTable.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    _mainTable.footerRefreshingText = @"正在加载中";
}
-(void)clickAdv:(NSInteger)pageIndex {
    [MobClick event:@"goToInfo"];
    if (_topIdArray.count == 0) {
        return;
    } else {
        InfoViewController *info = [[InfoViewController alloc]init];
        info.hidesBottomBarWhenPushed = YES;
        info.titleLabel = [_topTitleArray objectAtIndex:pageIndex];
        info.Id = [_topIdArray objectAtIndex:pageIndex];
        [self.navigationController pushViewController:info animated:YES];
    }
}
- (void)footerRereshing {
    if (_isleft) {
        [self getData];
    } else {
        [self getInfo];
    }
}
-(void)getData {
    [self showIndeterminateProgress];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://115.29.243.47/cartoonWorld/interface.php/news?keyid=1&page=%d&fetchSize=20",_i]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc]initWithURL:url];
    request.delegate = self;
    request.username = @"start";
    [request startSynchronous];
    _i++;
}
-(void)requestFinished:(ASIHTTPRequest *)request {
    if (_i == 1) {
        _titleArray = [[NSMutableArray alloc]init];
        _idArray = [[NSMutableArray alloc]init];
        _imgArray = [[NSMutableArray alloc]init];
        _infoArray = [[NSMutableArray alloc]init];
        _topIdArray = [[NSMutableArray alloc]init];
        _topImgArray = [[NSMutableArray alloc]init];
        _topTitleArray = [[NSMutableArray alloc]init];
        _subTitle = [[NSMutableArray alloc]init];
        _subIdArray = [[NSMutableArray alloc]init];
        _subImgArray = [[NSMutableArray alloc]init];
        _subInfoArray = [[NSMutableArray alloc]init];
    }
    SBJsonParser *jsonP = [[SBJsonParser alloc]init];
    if ([request.username isEqualToString:@"start"]) {
        NSArray *array =[[jsonP objectWithData:[request responseData]]objectForKey:@"ads"];
        for (int i = 0; i < array.count; i++) {
            [_topTitleArray addObject:[[array objectAtIndex:i] objectForKey:@"news_title"]];
            [_topImgArray addObject:[[array objectAtIndex:i] objectForKey:@"pic_url"]];
            [_topIdArray addObject:[[array objectAtIndex:i] objectForKey:@"record_id"]];
        }
        if (_infoArray.count == 0) {
            [self creatController];
        }
        NSArray *array1 = [[jsonP objectWithData:[request responseData]] objectForKey:@"news"];
        for (int i = 0; i < array1.count; i++) {
            [_titleArray addObject:[[array1 objectAtIndex:i] objectForKey:@"title"]];
            [_idArray addObject:[[array1 objectAtIndex:i] objectForKey:@"id"]];
            [_imgArray addObject:[[array1 objectAtIndex:i] objectForKey:@"small_pic"]];
            [_infoArray addObject:[[array1 objectAtIndex:i] objectForKey:@"intro"]];
        }
        [_mainTable reloadData];
    } else {
        NSArray *array1 = [[jsonP objectWithData:[request responseData]] objectForKey:@"news"];
        for (int i = 0; i < array1.count; i++) {
            [_subTitle addObject:[[array1 objectAtIndex:i] objectForKey:@"title"]];
            [_subIdArray addObject:[[array1 objectAtIndex:i] objectForKey:@"id"]];
            [_subImgArray addObject:[[array1 objectAtIndex:i] objectForKey:@"small_pic"]];
            [_subInfoArray addObject:[[array1 objectAtIndex:i] objectForKey:@"intro"]];
        }
        [_mainTable reloadData];
    }
    [HUD hide:YES];
    [_mainTable footerEndRefreshing];
}

-(void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"请求失败");
}
-(void)segmentAction:(UIButton *)sender {
    switch (sender.tag) {
        case 1: {
            _left.backgroundColor = [UIColor colorWithRed:0.93 green:0.42 blue:0.29 alpha:1];
            _right.backgroundColor = [UIColor colorWithRed:0.9 green:0.76 blue:0.56 alpha:1];
            _back.backgroundColor = [UIColor colorWithRed:0.93 green:0.42 blue:0.29 alpha:1];
            _isleft = YES;
            [_mainTable reloadData];
        }
            break;
        case 2: {
            if (_subTitle.count == 0) {
                [self getInfo];
            }
            _left.backgroundColor = [UIColor colorWithRed:0.91 green:0.62 blue:0.53 alpha:1];
            _right.backgroundColor = [UIColor colorWithRed:0.96 green:0.61 blue:0.15 alpha:1];
            _isleft = NO;
            _back.backgroundColor = [UIColor colorWithRed:0.96 green:0.61 blue:0.15 alpha:1];
            [_mainTable reloadData];
        }
            break;
        default:
            break;
    }
}

-(void)getInfo {
    [self showIndeterminateProgress];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://115.29.243.47/cartoonWorld/interface.php/news?keyid=2&page=%d&fetchSize=20",_j]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc]initWithURL:url];
    request.delegate = self;
    request.username = @"info";
    [request startAsynchronous];
    _j++;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isleft) {
        return _infoArray.count;
    } else {
        return _subInfoArray.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    _cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if(_cell == nil){
        _cell = [[InfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    } else {
        for (UIView *view in [_cell.contentView subviews]) {
            [view removeFromSuperview];
        }
    }
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_isleft) {
        [_cell.image setImageURLStr:[_imgArray objectAtIndex:indexPath.row] placeholder:[UIImage imageNamed:@"1"]];
        
        _cell.titleLabel.text = [_titleArray objectAtIndex:indexPath.row];
        
        _cell.infoLabel.text = [_infoArray objectAtIndex:indexPath.row];
        
    } else {
        [_cell.image setImageURLStr:[_subImgArray objectAtIndex:indexPath.row] placeholder:[UIImage imageNamed:@"1"]];
        
        _cell.titleLabel.text = [_subTitle objectAtIndex:indexPath.row];
        
        _cell.infoLabel.text = [_subInfoArray objectAtIndex:indexPath.row];
    }
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 66, 320, 1)];
    line.backgroundColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.86 alpha:1];
    [_cell.contentView addSubview:line];
    
    return _cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    InfoViewController *info = [[InfoViewController alloc]init];
    if (_isleft) {
        info.Id = [_idArray objectAtIndex:indexPath.row];
        info.titleLabel = [_titleArray objectAtIndex:indexPath.row];
    } else {
        info.Id = [_subIdArray objectAtIndex:indexPath.row];
        info.titleLabel = [_subTitle objectAtIndex:indexPath.row];
    }
    [MobClick event:@"goToInfo"];

    info.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:info animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
